package org.mashart.pink.m.ws;

import org.mashart.pink.m.store.RecordManager;
import org.mashart.pink.m.store.FileManager;

/**
 * Connector for file I/O.
 * The GPS data are first stored in RecordStore.
 * Before terminating, the RecordStore is transfered into a file on the mobile device,
 * and the RecordStore is then deleted.
 */
public class FileConnector implements WsConnector{

    /**
     * Record Manager, implements the operation on record store.
     */
    private RecordManager recordManager;

    /**
     * File Connector, implements the operation on file system
     */
    private FileManager fileManager;

    /**
     * Configure.
     * @return
     */
    public int configure(){
        return 1;
    }

    /**
     * Initialize the record store.
     * @return
     */
    public int initialize(){
        int res = 1;
        fileManager = new FileManager();
        if ( !fileManager.isAPIAvailable() || fileManager.initialize() < 1 )
        {
            // File connection API is not available
            res = -1;
        }
        // initialize the record manager
        recordManager = RecordManager.getInstance();
        if( recordManager.open() < 1 ){
            res = -1;
        }
        return res;
    }

    /**
     * Store the data in bytes.
     * @param b
     * @return
     */
    public int push(byte[] b){
        return recordManager.insert(b);
    }

    /**
     * Close the record store. The records should remains on the mobile phone,
     * until the <code>RecordStoreConnector</code> is initialzed again.
     * However, depending on the implementation of the mobilephone,
     * it is possible that the RecordStore can not survive through battery changes, failures, or reboots.
     * @return
     */
    public int terminate(){
        int res;
        // save the RecordStore
        res = fileManager.save(recordManager);
        // close the RecordStore
        recordManager.close();
        // delete the RecordStore
//        if(res == 1){
            recordManager.delete();
//        }
        return res;
    }

}
